package org.bean.box.tcp;


import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.filterchain.IoFilter;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.net.InetSocketAddress;

@Slf4j
@Component
public class TCPServer {

    @Value("${inter.socket.address}")
    private String port;

    @Bean
    public IoAcceptor ioAcceptor(TcpHandler tcpHandler) throws IOException {
        log.info("startServer");

        IoAcceptor ioAcceptor = new NioSocketAcceptor();
        ioAcceptor.getSessionConfig().setReadBufferSize(1024 * 1024 * 10);
        ioAcceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 30);
        IoFilter ioFilter = new ProtocolCodecFilter(new TcpFactory());
        ioAcceptor.getFilterChain().addLast("codec", ioFilter);
        ioAcceptor.setHandler(tcpHandler);
        ioAcceptor.bind(new InetSocketAddress(Integer.parseInt(port)));
        return ioAcceptor;
    }
}
